package com.eastfair.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eastfair.auth.dao.UserRoleMapper;
import com.eastfair.auth.entity.*;
import com.eastfair.auth.service.RoleService;
import com.eastfair.auth.service.UserRoleService;
import com.eastfair.auth.vo.RoleVo;
import com.eastfair.boot.service.SuperCacheServiceImpl;
import com.eastfair.boot.service.SuperServiceImpl;

import com.eastfair.cache.auth.UserRoleCacheKeyBuilder;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.model.CacheKeyBuilder;
import com.eastfair.point.business.auth.BusinLoadUserPermissOfOrgPoint;
import com.eastfair.projectcore.entity.ProjectDb;
import com.eastfair.uid.baidu.rule.SnowFlakeRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//import com.baomidou.dynamic.datasource.annotation.DS;

import static com.eastfair.core.base.R.SUCCESS_CODE;

/**
 * <p>
 * 业务实现类
 * 用户角色表
 * </p>
 *
 * @author ligang
 * @date 2022-06-06
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class UserRoleServiceImpl extends SuperCacheServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Autowired
    RoleService roleService;
    @Autowired
    SnowFlakeRole snowFlakeRole;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<UserRole> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }


    @Override
    public CacheKeyBuilder getCacheKeyBuilder() {
        return new UserRoleCacheKeyBuilder();
    }

    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerSave(UserRole model) {
        model.setId(snowFlakeRole.findUidSimple());
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        model.setTeamId(ContextUtil.getTeamId());
        return R.successDef();
    }

    @Override
    public R addUserRole(List<Long> userIdList, List<Long> roleIds) {
        if (roleIds != null && !roleIds.isEmpty()) {
            for (Long userid : userIdList) {
                for (Long roleId : roleIds) {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(userid);
                    userRole.setRoleId(roleId);
                    save(userRole);
                }
            }
        }
        return R.success();
    }

    @Override
    public R updUserRole(List<Long> userIdList, List<Long> roleIds) {
        //剔除角色
        removeUserRole(userIdList, null);
        //添加角色
        addUserRole(userIdList, roleIds);
        return R.success();
    }

    @Override
    public R removeUserRole(List<Long> userIdList, List<Long> roleIds) {
        List<UserRole> userRoleList = null;
        if (roleIds != null && !roleIds.isEmpty() && userIdList != null && !userIdList.isEmpty()) {
            userRoleList = list(null, userIdList, roleIds);
        } else if (roleIds != null && !roleIds.isEmpty() && (userIdList == null || userIdList.isEmpty())) {
            userRoleList = list(null, null, roleIds);
        } else if ((roleIds == null || roleIds.isEmpty()) && (userIdList != null && !userIdList.isEmpty())) {
            userRoleList = list(null, userIdList, null);
        }

        if (userRoleList != null && !userRoleList.isEmpty()) {
            for (UserRole userRole : userRoleList) {
                userRole.setIsDeleted(BusinessConstant.DELETE_YES);
                updateById(userRole);
            }
        }
        return R.success();
    }

    @Override
    public R removeOfRole(List<Long> roleIds) {
        List<UserRole> userRoleList = list(null, null, roleIds);
        if (userRoleList != null && !userRoleList.isEmpty()) {
            for (UserRole userRole : userRoleList) {
                userRole.setIsDeleted(BusinessConstant.DELETE_YES);
                updateById(userRole);
            }
        }
        return R.success();
    }

    @Override
    public List<UserRole> findOfRole(List<Long> roleIds) {
        return list(null, null, roleIds);
    }

    @Override
    public List<UserRole> findOfUser(List<Long> userIds) {
        return list(null, userIds, null);
    }

    @Override
    public List<UserRole> list(UserRole userRole, List<Long> userIds, List<Long> roleIds) {
        //查询
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        if (userRole != null) {
            if (userRole.getId() != null) {
                queryWrapper.lambda().eq(UserRole::getId, userRole.getId());
            }
            if (userRole.getRoleId() != null) {
                queryWrapper.lambda().eq(UserRole::getRoleId, userRole.getRoleId());
            }

            if (userRole.getUserId() != null) {
                queryWrapper.lambda().eq(UserRole::getUserId, userRole.getUserId());
            }
        }
        if (userIds != null && !userIds.isEmpty()) {
            queryWrapper.lambda().in(UserRole::getUserId, userIds);
        }
        if (roleIds != null && !roleIds.isEmpty()) {
            queryWrapper.lambda().in(UserRole::getRoleId, roleIds);
        }
        queryWrapper.lambda().eq(UserRole::getIsDeleted, BusinessConstant.DELETE_NO);
        return list(queryWrapper);
    }

    @Override
    public Map<Long, List<UserRole>> findMapOfUser(List<Long> userIds) {
        Map<Long, List<UserRole>> result = new HashMap<>();
        List<UserRole> userRoleList = findOfUser(userIds);
        if (userRoleList == null || userRoleList.isEmpty()) {
            return null;
        }
        for (Long userId : userIds) {
            result.put(userId, userRoleList.stream().filter(s -> s.getUserId().equals(userId)).collect(Collectors.toList()));
        }
        return null;
    }

    @Override
    public Map<Long, List<RoleVo>> findRoleMapOfUser(List<Long> userIds) {
        Map<Long, List<RoleVo>> result = new HashMap<>();
        List<UserRole> userRoleList = findOfUser(userIds);
        if (userRoleList == null || userRoleList.isEmpty()) {
            return null;
        }
        List<Long> roleIds = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        List<Role> roleList = roleService.listByIds(roleIds);
        if (roleList == null || roleList.isEmpty()) {
            return null;
        }
        for (Long userId : userIds) {
            List<Long> userRoleId = userRoleList.stream().filter(s -> s.getUserId().equals(userId)).map(UserRole::getRoleId).collect(Collectors.toList());
            if (userRoleId != null && !userRoleId.isEmpty()) {
                result.put(userId, roleService.doToVos(roleList.stream().filter(s -> userRoleId.contains(s.getId())).collect(Collectors.toList())));
            }
        }
        return result;
    }


}
